﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Read.Api.Application.Command;
using B.S.BaseData.Read.Api.Dtos;
using CSRedis;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json;

namespace B.S.BaseData.Read.Api.Application.CommandHander
{
    public class UserLoginCommandHander : IRequestHandler<UserLoginCommand, ApiResult<UserLoginDto>>
    {
        private readonly IMapper mapper;
        private readonly ILogger<UserLoginCommandHander> logger;
        private readonly ISqlSugarClient db;
        private readonly CSRedisClient cs = new CSRedisClient("123.57.166.20:6379");

        public UserLoginCommandHander(IMapper mapper, ILogger<UserLoginCommandHander> logger, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.logger = logger;
            this.db = db;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<UserLoginDto>> Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {
            ApiResult<UserLoginDto> result = new ApiResult<UserLoginDto>();

            var list = new User();
            var role = new UserRole();

            // 存储登录用户的 Userid 到 Redis
            var val = cs.Get($"User:{request.UserName}");

            //当Redis数据库中没有登录人信息给Redis进行添加当前登录人
            if (val == null)
            {

                var model = db.Queryable<User>().Where(x => x.UserName == request.UserName).First();

                UserLoginDto dto = mapper.Map<UserLoginDto>(model);

                list = await db.Queryable<User>().Where(x => x.UserName == request.UserName).FirstAsync();
                if (list == null)
                {
                    result.Code = ApiEnum.用户名不存在;
                    result.Msg = ApiEnum.用户名不存在.ToString();
                    return result;
                }

                role = await db.Queryable<UserRole>().Where(x => x.UserId == list.UserId).FirstAsync();

                if (list.Password != request.Password)
                {
                    result.Code = ApiEnum.密码错误;
                    result.Msg = ApiEnum.密码错误.ToString();
                    return result;
                }
                else
                {
                    // 存储 Userid 到 Redis
                    cs.Set($"User:{dto.UserName}", dto, TimeSpan.FromHours(12));

                    result.Code = ApiEnum.登录成功;
                    result.Msg = ApiEnum.登录成功.ToString();
                    var id = Convert.ToString(list.UserId);
                    var rid = Convert.ToString(role?.RoleId);
                    result.Token = CreateTokenString(id, rid);
                    result.Data = mapper.Map<UserLoginDto>(list);

                    return result;
                }
            }
            else
            ///有问题
            {
                // 存储 Userid 到 Redis
                var entoty = cs.Get($"User:{request.UserName}");

                result.Code = ApiEnum.登录成功;
                result.Msg = ApiEnum.登录成功.ToString();
                var id = Convert.ToString(list.UserId);
                var rid = Convert.ToString(role?.RoleId);
                result.Token = CreateTokenString(id, rid);
                result.Data = JsonSerializer.Deserialize<UserLoginDto>(entoty);

                return result;
            }
        }
        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public string CreateTokenString(string uid, string rid)
        {
            var signingAlgorithm = SecurityAlgorithms.HmacSha256;
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, uid),
                new Claim(ClaimTypes.Role, rid?? "")
            };
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            var signingKey = new SymmetricSecurityKey(secretByte);
            var signingCredentials = new SigningCredentials(signingKey, signingAlgorithm);
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                claims: claims,
                notBefore: DateTime.UtcNow,
                expires: DateTime.Now.AddDays(1),
                signingCredentials: signingCredentials
            );
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}